package com.mchsdk.paysdk.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.baidu.api.AccessTokenManager;
import com.baidu.api.Baidu;
import com.baidu.api.BaiduDialog;
import com.baidu.api.BaiduDialogError;
import com.baidu.api.BaiduException;
import com.mchsdk.paysdk.bean.LoginModel;
import com.mchsdk.paysdk.common.Constant;
import com.mchsdk.paysdk.utils.AccessTokenKeeper;
import com.mchsdk.paysdk.utils.MCLog;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by Administrator on 2017/9/28/028.
 * 第三方登录
 */

public class ThirdLoginActivity extends MCBaseActivity {

    private static final String TAG = "ThirdLoginActivity";

    private SsoHandler mSsoHandler;
    private Baidu baidu;

    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;

        selectThirdLoginType(getIntent().getExtras());

    }

    private void selectThirdLoginType(Bundle bundle) {
        if (null != bundle) {
            String logintype = bundle.getString("logintype", "");
            MCLog.w(TAG, "logintype:" + logintype);
            if ("qqlogin".equals(logintype)) {
                String qqappidlogin = bundle.getString("qqappid", "");
                qqlogin(qqappidlogin);
            } else if ("qqloginoff".equals(logintype)) {
                String qqappidexit = bundle.getString("qqappid");
                qqloginoff(qqappidexit);
            } else if ("wblogin".equals(logintype)) {
                String wbappkey = bundle.getString("wbappkey", "");
                String wbredirectUrl = bundle.getString("wbredirectUrl",
                        "http://open.weibo.com/apps/3275362030/privilege/oauth");
                String wbsoap = bundle.getString("wbsoap", "");
                wblogin(wbappkey, wbredirectUrl, wbsoap);
            } else if ("bdlogin".equals(logintype)) {
                String clientId = bundle.getString("bdclientid", "");
                baidulogin(clientId);
            } else if ("wxlogin".equals(logintype)) {
                Constant.WXAPPID = bundle.getString("wxappid", "");
                wxLogin();
            }
        } else {
            LoginModel.instance().loginFail();
            finish();
        }
    }

    void wxLogin() {
        MCLog.e(TAG, "start wx login");
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.WXAPPID);
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo";
        api.sendReq(req);
        finish();
    }

    void qqlogin(String qqappid) {
        Tencent mTencent = Tencent.createInstance(qqappid, ThirdLoginActivity.this);
        if (!mTencent.isSessionValid()) {
            mTencent.login(ThirdLoginActivity.this, "all", qqLoginListener);
        }
    }

    void qqloginoff(String qqappid) {
        Tencent tencent = Tencent.createInstance(qqappid, ThirdLoginActivity.this);
        if (tencent.isSessionValid()) {
            tencent.logout(ThirdLoginActivity.this);
        }
    }

    void wblogin(String wbappkey, String redirectUrl, String soap) {
//        WeiBoLogin weiboLogin = new WeiBoLogin(context, wbappkey, Constants.REDIRECT_URL, Constants.SCOPE);
//        WeiBoLogin.mSsoHandler.authorize(weiboLogin);

        AuthInfo mAuthInfo = new AuthInfo(context, wbappkey, redirectUrl, soap);
        mSsoHandler = new SsoHandler((Activity) context, mAuthInfo);
        mSsoHandler.authorize(wbAuthListener);
    }


    void baidulogin(String clientId) {
        //是否每次授权都强制登陆
//        boolean isForceLogin = false;
//        boolean isConfirmLogin = true;
        MCLog.w(TAG, "clientId:" + clientId);
        baidu = new Baidu(clientId, ThirdLoginActivity.this);
        baidu.authorize(ThirdLoginActivity.this, false, true, bdLoginListener);
    }

    private BaiduDialog.BaiduDialogListener bdLoginListener = new BaiduDialog.BaiduDialogListener() {
        @Override
        public void onComplete(Bundle bundle) {
            AccessTokenManager atm = baidu.getAccessTokenManager();
            returnBaiDuInfo(atm.getAccessToken());
        }

        @Override
        public void onBaiduException(BaiduException e) {
            MCLog.w(TAG, "bd login Exception:" + e.getMessage());
            returnBaiDuInfo("");
        }

        @Override
        public void onError(BaiduDialogError e) {
            MCLog.w(TAG, "bd login DialogError:" + e.getMessage());
            returnBaiDuInfo("");
        }

        @Override
        public void onCancel() {
            MCLog.w(TAG, "bd cancel login");
            returnBaiDuInfo("");
        }
    };


    private void returnBaiDuInfo(String accessToken) {
        Intent intent = new Intent(ThirdLoginActivity.this, MCControlResActivity.class);

        Bundle bundle = new Bundle();
        bundle.putString("restype", "bdlogin");
        bundle.putString("accessToken", accessToken);
        intent.putExtras(bundle);
        startActivity(intent);
        finish();
    }

    private IUiListener qqLoginListener = new IUiListener() {
        @Override
        public void onComplete(Object response) {
            MCLog.e(TAG, "--QQ授权--");
            if (null == response) {
                MCLog.w(TAG, "QQ授权失败");
                returnQQInfo("", "");
                return;
            }
            JSONObject jsonResponse = (JSONObject) response;
            if (jsonResponse.length() == 0) {
                MCLog.w(TAG, "QQ授权失败");
                returnQQInfo("", "");
                return;
            }
            MCLog.w(TAG, "QQ授权成功");
            String openId = "", accessToken = "";
            try {
                openId = ((JSONObject) response).getString(com.tencent.connect.common.Constants.PARAM_OPEN_ID);
                accessToken = ((JSONObject) response)
                        .getString(com.tencent.connect.common.Constants.PARAM_ACCESS_TOKEN);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            MCLog.w(TAG, "QQLogin,openId:" + openId + ",accessToken:" + accessToken);
            returnQQInfo(openId, accessToken);
        }

        @Override
        public void onError(UiError uiError) {
            MCLog.w(TAG, "qq login: errorCode" + uiError.errorCode +
                    ", errorMessage:" + uiError.errorMessage +
                    ", errorDetail:" + uiError.errorDetail);
            returnQQInfo("", "");
        }

        @Override
        public void onCancel() {
            MCLog.w(TAG, "qq cancel login");
            returnQQInfo("", "");
        }
    };

    private void returnQQInfo(String openId, String accessToken) {
        Intent intent = new Intent(ThirdLoginActivity.this, MCControlResActivity.class);

        Bundle bundle = new Bundle();
        bundle.putString("restype", "qqlogin");
        bundle.putString("openId", openId);
        bundle.putString("accessToken", accessToken);
        intent.putExtras(bundle);
        startActivity(intent);
        finish();
    }

    private WeiboAuthListener wbAuthListener = new WeiboAuthListener() {
        @Override
        public void onComplete(Bundle bundle) {
            Oauth2AccessToken accessToken = Oauth2AccessToken.parseAccessToken(bundle);
            if (accessToken != null && accessToken.isSessionValid()) {
                AccessTokenKeeper.writeAccessToken(getApplicationContext(), accessToken);

                Oauth2AccessToken mAccessToken = AccessTokenKeeper.readAccessToken(context);
                String wbuid = mAccessToken.getUid();
                MCLog.w(TAG, "wbuid:" + wbuid);
                returnWBInfo(wbuid, accessToken.getToken());
            } else {
                returnWBInfo("", "");
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
            returnWBInfo("", "");
            MCLog.w(TAG, "wb login:" + e.getMessage());
        }

        @Override
        public void onCancel() {
            returnWBInfo("", "");
            MCLog.w(TAG, "wb cancel login");
        }
    };


    private void returnWBInfo(String userid, String accessToken) {
        Intent intent = new Intent(ThirdLoginActivity.this, MCControlResActivity.class);

        Bundle bundle = new Bundle();
        bundle.putString("restype", "wblogin");
        bundle.putString("wbuid", userid);
        bundle.putString("accessToken", accessToken);
        intent.putExtras(bundle);
        startActivity(intent);
        finish();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == com.tencent.connect.common.Constants.REQUEST_LOGIN ||
                requestCode == com.tencent.connect.common.Constants.REQUEST_APPBAR) {
            Tencent.onActivityResultData(requestCode, resultCode, data, qqLoginListener);
        } else {
            if (mSsoHandler != null) {
                mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (null != baidu) {
//            baidu.clearAccessToken();
            baidu = null;
        }
    }
}
